package com.rongxun.base;

import android.content.Context;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import java.util.List;

/**
 * @author yinhui
 * @classname: IBaseAdapter
 * @Description:
 * @date 2016/7/12 11:50
 */
public abstract class IBaseAdapter<T> extends BaseAdapter {

	protected Context mContext;
	protected List<T> mList;
	protected int     mCount;

	public IBaseAdapter(Context c) {
		this.mContext = c;
	}

	@SuppressWarnings("unchecked")
	public void setList(List<? extends T> list) {
		mList = (List<T>) list;
		notifyDataSetChanged();
	}

	public void addItem(T t) {
		if(t != null){
			mList.add(t);
		}
		notifyDataSetChanged();
	}

	public void addItems(List<T> list) {
		if(list != null){
			for (T t : list) {
				mList.add(t);
			}
		}
		notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		mCount = (mList != null) ? mList.size() : 0;
		return mCount;
	}

//	@Override
//	public boolean isEnabled(int position) {
//		return position > 0 || getHeadersCount() > 0 ? super.isEnabled(position) : false;
//	}

	@Override
	public T getItem(int position) {
		return (mList != null) ? mList.get(position) : null;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	abstract public View getView(int position, View convertView, ViewGroup parent);

	/**
	 * 该方法用来取代繁琐的viewHolder缓存方式
	 * @param convertView
	 * @param id
	 * @param <T>
     * @return
     */
	@SuppressWarnings({ "unchecked", "hiding" })
	protected <T extends View> T getAdapterView(View convertView, int id) {
		SparseArray<View> viewHolder = (SparseArray<View>) convertView.getTag();
		if (viewHolder == null) {
			viewHolder = new SparseArray<View>();
			convertView.setTag(viewHolder);
		}
		View childView = viewHolder.get(id);
		if (childView == null) {
			childView = convertView.findViewById(id);
			viewHolder.put(id, childView);
		}
		return (T) childView;
	}

	public List<T> getList() {
		return mList;
	}

	/** 删除单个 */
	public void remove(int position) {
		mList.remove(position);
		notifyDataSetChanged();
	}

	/** 删除单个 */
	public void remove(T t) {
		mList.remove(t);
		notifyDataSetChanged();
	}

	/** 删除多个 */
	public void remove(List<Integer> positions) {
		for (int i = 0;i < positions.size();i++){
			mList.remove(positions.get(i) - i);
		}
	}

	/**
	 * 删除所有
	 */
	public void clearItem() {
		clearList();
		notifyDataSetChanged();
	}

	public void clearList(){
		if(mList != null){
			mList.clear();
		}
	}

	@Override
	public boolean hasStableIds() {
		return true;
	}

	protected void showImage(String img_url, ImageView iv) {
		if(img_url == null){
			return;
		}
	}

}
